import { store } from "@/store";

import UserAPI, { type UserForm } from "@/api/system/user.api";

import { setAccessToken } from "@/utils/auth";

export const useRegisterStore = defineStore("register", () => {
  const userInfo = useStorage<UserForm>("userInfo", {} as UserForm);

  /**
   * 登录
   *
   * @param {UserForm}
   * @returns
   */
  function register(loginData: UserForm) {
    return new Promise<void>((resolve, reject) => {
      UserAPI.register(loginData)
        .then((data) => {
          userInfo.value.password = "";
          userInfo.value.confirmPassword = "";
          const { accessToken } = data;
          setAccessToken(accessToken);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 清除表单数据
   */
  function clear() {
    return new Promise<void>(() => {
      userInfo.value = {};
    });
  }

  return {
    userInfo,
    register,
    clear,
  };
});

export function useRegisterStoreHook() {
  return useRegisterStore(store);
}
